import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/home/index.vue'
// 解决 TypeScript 对 .vue 文件的类型声明问题
// @ts-ignore
import detail from '../views/home/detail.vue'
// @ts-ignore
import main from '../views/home/main.vue'
// @ts-ignore
import user from '../views/home/user.vue'
// @ts-ignore
import edituser from '../views/home/edituser.vue'
// @ts-ignore
import projects from '../views/projects/index.vue'
// @ts-ignore
import login from '../views/login/index.vue'
// @ts-ignore
import aichat from '../views/aichat/index.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', redirect: '/login' },

    {
      path: '/',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: 'index',
          name: 'index',
          component: main,
        },
        {
          path: 'detail',
          name: 'detail',
          component: detail,
        },

        {
          path: 'user',
          name: 'user',
          component: user,
        },
        {
          path: 'edituser',
          name: 'edituser',
          component: edituser,
        },
        {
          path: 'projects',
          name: 'projects',
          component: projects,
        },
        {
          path: 'aichat',
          name: 'aichat',
          component: aichat,
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: login,

    }
  ]
})

// 全局前置守卫：未登录跳转到登录页
router.beforeEach((to, from, next) => {
  // 允许直接访问登录页
  if (to.path === '/login') {
    return next();
  }
  // 判断登录状态
  const isLogin = localStorage.getItem('isLogin');
  if (!isLogin) {
    // 未登录，跳转到登录页
    return next({ path: '/login' });
  }
  // 已登录，正常访问
  next();
});

export default router
